import * as THREE from "three";
import { gsap } from "gsap";

export default class DropRotation {
  constructor() {
    this.chairModels = [];
    this.bodyModel = new THREE.Mesh();
    this.main = new THREE.Group();

    this.rotation = 0;
    this.height = 2;

    gsap.timeline({ yoyo: true, repeat: -1, repeatDelay: 0 })
      .to(this, { rotation: Math.PI * 2, height: 8.5, duration: 1.5, ease: "power1.inOut" });
  }

  add(mesh) {
    if (mesh.userData.name === "drop-rotation-chair") {
      this.chairModels.push(mesh);
    } else {
      this.bodyModel = mesh;
    }
  }

  build() {
    const defaultPosition = this.bodyModel.position.clone();
    this.bodyModel.position.set(0, 0, 0);
    this.main.add(this.bodyModel);
    this.main.position.copy(defaultPosition);

    const chair = new THREE.Group();
    this.chairModels.forEach((model) => {
      model.position.set(0, 0, 0);
      chair.add(model);
    });
    this.main.add(chair);

    const nums = 14;
    const rand = Math.PI * 2 / nums;
    for (let i = 1; i < nums; i++) {
      const n = chair.clone();
      n.rotation.set(0, 0, rand * i);
      this.main.add(n);
    }
  }

  update() {
    this.main.rotation.z = this.rotation;
    this.main.position.z = this.height;
  }
}